#pragma once
#include <iostream>
#include <cstring>
#include <pthread.h>
#include <cstdint>
#include <cstdio>
#include <functional>


namespace ThreadModle
{

    static uint32_t number = 1;

    class Thread
    {
        using func_t = std::function<void()>;
    private:
        void EnableDetach()
        {
            std::cout << "线程被分离了" << std::endl;
            _isdetach = true;
        }

        void EnableRunning()
        {
            _isrunning = true; 
        }
        
        static void* Routine(void* args)
        {
            Thread* self = static_cast<Thread*>(args);
            self->EnableRunning();
            if(self->_isdetach)
                self->Detach();
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();

            return nullptr;
        }

    public:
        Thread(func_t func):_func(func), _tid(0), _isrunning(false), _isdetach(false), res(nullptr)
        {
            _name = "thread-" + std::to_string(number++);
        }

        void Detach()
        {
            if(_isdetach)
                return;
            if(_isrunning)
                pthread_detach(_tid);
            EnableDetach();
        }

        bool Start()
        {
            if(_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if(n != 0)
            {
                std::cerr << " create thread error: " << strerror(n) << std::endl;
                return false;
            }
            else
            {
                std::cout << _name << " create success " << std::endl;
                return true;
            }
        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                {
                    std::cerr << " cancel thread error: " << strerror(n) << std::endl;
                    return false; 
                }
                else
                {
                    _isrunning = false;
                    std::cout << _name << " stop " << std::endl;
                    return true;
                }

            }
            return false;
        }


        void Join()
        {
            if(_isdetach)
            {
                std::cout << " 您的线程已经分离了，不能进行Join " << std::endl;
                return;
            }
            int n = pthread_join(_tid, &res);
            if(n != 0)
            {
                std::cerr << "thread join error: " << strerror(n) << std::endl;
                return;
            }
            else
            {
                std::cerr << " join success " << std::endl;
            }
        }

        ~Thread()
        {}
        
    private:
        pthread_t _tid;
        bool _isrunning;
        bool _isdetach;
        void* res;
        std::string _name;
        func_t _func;
    };

}










